/*
 * Copyright 2015 Alan.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package me.alanz.screencapture.tool;

import me.alanz.screencapture.model.Setting;
import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * created on 2015-6-15 15:55:08
 *
 * @author Alan
 */
public class XMLTool {

    private static final Logger logger = Logger.getLogger(XMLTool.class.getName());
    public static String SEETING_PATH = "setting.xml";

    public static void saveSetting(Setting setting) {
        OutputStream out;
        try {
            out = new FileOutputStream(SEETING_PATH);
            try (java.beans.XMLEncoder encoder = new XMLEncoder(out)) {
                encoder.writeObject(setting);
            }
        } catch (Exception e) {
            logger.log(Level.INFO, "", e);
        }
    }

    public static Setting readSetting() {
        try {
            List objList = XMLTool.objectXMLDecoder(SEETING_PATH);
            if (objList.size() > 0) {
                return (Setting) objList.get(0);
            }
        } catch (Exception ex) {
            logger.log(Level.SEVERE, SEETING_PATH);
            Logger.getLogger(XMLTool.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }

    public static List objectXMLDecoder(String objSource)
            throws FileNotFoundException, IOException, Exception {
        List objList = new ArrayList();
        File fin = new File(objSource);
        try (FileInputStream fis = new FileInputStream(fin);
                XMLDecoder decoder = new XMLDecoder(fis)) {
            Object obj;
            try {
                if ((obj = decoder.readObject()) != null) {
                    objList.add(obj);
                }
            } catch (Exception e) {
            }
        }
        return objList;
    }
}
